﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wq.Extensions;
using Wq.Extensions.Common;
using Wq.Extensions.Repository;
using Wq.ManagerService.Entities;
using Wq.ManagerService.Models;
using Wq.Model;


namespace Wq.ManagerService
{
    /// <summary>
    /// 日志
    /// </summary>
    public class LogService : SqlSugarBaseRepository<OperationLogInfo>, IAddSingleton
    {
        private IHttpContextAccessor accessor;
        private JwtUserModel manager = new JwtUserModel();
        private string ipAddress;

        public LogService(IHttpContextAccessor accessor) =>this.accessor = accessor;    
        
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="log"></param>
        public void Create(LogModule module, string message)
        {
            manager = JWTHelper.SerializeJwt(accessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""));
            ipAddress = accessor.HttpContext.Connection.RemoteIpAddress.ToString();
            OperationLog log = new OperationLog
            {
                Module = module,
                Operator = manager.UserId.ObjToInt(),
                OperatorName = manager.UserName,
                OperatorAddress = ipAddress,
                Message = message,
            };
            var info = log.Map<OperationLogInfo>();
            info.OperatorAddress = ipAddress;
            info.Time = DateTime.Now;
            Context.Insertable(info).ExecuteCommand();

        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="log"></param>
        public void Create(List<OperationLog> logs)
        {
            manager = JWTHelper.SerializeJwt(accessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""));
            ipAddress = accessor.HttpContext.Connection.RemoteIpAddress.ToString();
            var list = logs.Map<OperationLogInfo>();
            list.ForEach(item => {
                item.Operator = manager.UserId.ObjToInt();
                item.OperatorName = manager.UserName;
                item.OperatorAddress = ipAddress;
                item.Time = DateTime.Now;
            });
            Context.Insertable(list).ExecuteCommand();
        }
    }
}
